package org.linlinjava.litemall.wx.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author wf_sxf@163.com
 * @date 2018-08-12 21:26
 */
public class NewImageUtils {
    /**
     * 10      *
     * 11      * @Title: 构造图片
     * 12      * @Description: 生成水印并返回java.awt.image.BufferedImage
     * 13      * @param file
     * 14      *            源文件(图片)
     * 15      * @param waterFile
     * 16      *            水印文件(图片)
     * 17      * @param x
     * 18      *            距离右下角的X偏移量
     * 19      * @param y
     * 20      *            距离右下角的Y偏移量
     * 21      * @param alpha
     * 22      *            透明度, 选择值从0.0~1.0: 完全透明~完全不透明
     * 23      * @return BufferedImage
     * 24      * @throws IOException
     * 25
     */
    public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException {
        // 获取底图
        BufferedImage buffImg = ImageIO.read(file);
        // 获取层图
        BufferedImage waterImg = ImageIO.read(waterFile);
        // 创建Graphics2D对象，用在底图对象上绘图
        Graphics2D g2d = buffImg.createGraphics();
        int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
        int waterImgHeight = waterImg.getHeight();// 获取层图的高度
        // 在图形和图像中实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 绘制
        g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
        g2d.dispose();// 释放图形上下文使用的系统资源
        return buffImg;
    }

    /**
     * 44      * 输出水印图片
     * 45      *
     * 46      * @param buffImg
     * 47      *            图像加水印之后的BufferedImage对象
     * 48      * @param savePath
     * 49      *            图像加水印之后的保存路径
     * 50
     */
    public File generateWaterFile(BufferedImage buffImg, String savePath) {
        int temp = savePath.lastIndexOf(".") + 1;
        try {
            File file = new File(savePath);
            ImageIO.write(buffImg, savePath.substring(temp), file);
            return file;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * @param args
     * @throws IOException IO异常直接抛出了
     * @author bls
     */
    public static void main(String[] args) throws IOException {
        String sourceFilePath = "D://template.jpg";
        String waterFilePath = "D://12.jpg";
        String saveFilePath = "D://123456.png";
        NewImageUtils newImageUtils = new NewImageUtils();
        //构建叠加层
        BufferedImage buffImg = NewImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath), 180, 380, 1f);
        //输出水印图片
        newImageUtils.generateWaterFile(buffImg, saveFilePath);
    }
}